﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SC.eWedding.BusinessLogic.Views;
using SC.eWedding.BusinessLogic.Handlers;
using System.Text;
using System.Configuration;

public partial class Proveedor_Controles_vdProductos : System.Web.UI.UserControl
{
    #region Interface

    // Evento Edit.
    public delegate void EditHandler();
    public event EditHandler Edit;

    // Evento ItemAdded.
    public delegate void ItemAddedHandler();
    public event ItemAddedHandler ItemAdded;

    //Evento PageIndexChanging
    public delegate void PageIndexChangingHandler();
    public event PageIndexChangingHandler PageIndexChanging;

    // Evento ItemDeleted.
    public delegate void ItemBorrarHandler();
    public event ItemBorrarHandler ItemBorrar;

    string _onClientAdd = "";
    public string OnClientAdd
    {
        set { _onClientAdd = value; }
        get { return _onClientAdd; }
    }

    string _onClientEdit = "";
    public string OnClientEdit
    {
        set { _onClientEdit = value; }
        get { return _onClientEdit; }
    }

    #endregion

    #region  Metodos Publicos

    public void CargarGrilla(List<ProdSerView> productos)
    {
        gvProducto.DataSource = productos;
        gvProducto.DataBind();
    }

    #endregion

    #region Metodos Privados

    private void CrearImagenes(ProdSerView prodSer, Table table)
    {
        if (prodSer.Fotos.Count > 0)
        {
            TableRow tr = new TableRow();
            TableRow trAppr = new TableRow();
            foreach (FotoView fo in prodSer.Fotos)
                tr.Cells.Add(CreateTableCell(fo.Id, "Foto"));
            table.Rows.Add(tr);
        }
    }

    private TableCell CreateTableCell(int id, string type)
    {
        TableCell tc = new TableCell();

        ImageButton image = new ImageButton();
        image.ImageUrl = "../../MakeThumbnail.aspx?id=" + id.ToString() + "&size=" + ConfigurationManager.AppSettings["TamañoImagen"].ToString() + "&tipo=" + type + "&source=db";

        tc.Controls.Add(image);

        return tc;
    }

    #endregion

    #region Eventos

    protected void Page_Load(object sender, EventArgs e)
    {
        btnAgregar.OnClientClick = OnClientAdd;
    }

    protected void gvProducto_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            int id = Convert.ToInt32(gvProducto.DataKeys[e.Row.RowIndex].Values["Id"]);
            Table table = (Table)e.Row.Cells[0].FindControl("TablaImagen");
            ProdSerView prod = ProdSerHandler.FindById(id);

            CrearImagenes(prod, table);
            ImageButton edit = (ImageButton)e.Row.Cells[e.Row.Cells.Count - 1].FindControl("btnEditar");
            edit.Attributes.Add("onclick", String.Format(this.OnClientEdit, id));
            ImageButton delete = (ImageButton)e.Row.Cells[e.Row.Cells.Count - 1].FindControl("btnBorrar");
            delete.Attributes.Add("onclick", "javascript: return (document.getElementById('" + hidConfirmation.ClientID + "').value = confirm('¿ Esta seguro de eliminar el producto?'));");

        }
    }

    protected void gvProducto_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        if (bool.Parse(hidConfirmation.Value))
        {
            int number = Convert.ToInt32(gvProducto.DataKeys[e.RowIndex].Values["Id"]);

            try
            {
                ProdSerView prod = ProdSerHandler.FindById(number);

                foreach (CaracteristicaView car in prod.Caracteristicas)
                    CaracteristicaHandler.Delete(car);

                foreach (ProdSerLocView loc in prod.Localidades)
                    ProdSerLocHandler.Delete(loc);

                foreach (FotoView fot in prod.Fotos)
                    FotoHandler.Delete(fot);


                ProdSerHandler.Delete(prod);

                if (ItemBorrar != null)
                    ItemBorrar();
            }
            catch
            {
                if (!Page.ClientScript.IsStartupScriptRegistered("script_Error"))
                {
                    StringBuilder script = new StringBuilder();

                    script.Append("<script language=\"jscript\">\n");
                    script.Append("   alert('Se produjo un error al intentar eliminar el producto');\n");
                    script.Append("</script>\n");

                    System.Web.UI.ScriptManager.RegisterStartupScript(this, this.GetType(), "script_Error", script.ToString(), false);
                }
            }
        }
    }

    protected void gvProducto_RowEditing(object sender, GridViewEditEventArgs e)
    {
        if (Edit != null)
            Edit();
    }

    protected void gvProducto_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvProducto.PageIndex = e.NewPageIndex;
        gvProducto.DataBind();
        if (PageIndexChanging != null)
            PageIndexChanging();
    }

    protected void btnAgregar_Click(object sender, EventArgs e)
    {
        if (ItemAdded != null)
            ItemAdded();
    }

    #endregion
}
